// #include "LightDigitGroup.h"
#include "Delay.h"
#include "MatrixKey.h"
#include "LCD1602.h"
#include <string.h>

uchar key;
char oper = ' ';
char digit1[14];
char digit2[14];

void LCD_ShowDigitArray(char *arr, uchar line) {
	uchar begin = 0;
	char i;
	LCD_Clear(line, 3, 14);
	for(i = 13; i >= 0; i--) {
		if(arr[i] != 0)
			begin = 1;
		if(begin == 1)
			LCD_ShowChar(line, 16 - i, arr[i] + '0');
	}
}

void InsertDigit(char value) {
	char i;
	if(digit2[13] != 0)
		return;
	for(i = 13; i > 0; i--)
		digit2[i] = digit2[i - 1];
	digit2[0] = value;
	LCD_ShowDigitArray(digit2, 2);
}

void Move() {
	memcpy(digit1, digit2, sizeof(char) * 14);
	memset(digit2, 0, sizeof(char) * 14);
	LCD_ShowDigitArray(digit1, 1);
	LCD_Clear(2, 3, 14);
}

void Sum() {
	char i;
	for(i = 0; i < 14; i++)
		digit1[i] += digit2[i];
	for(i = 0; i < 14; i++) {
		if(digit1[i] > 9) {
			if(i == 13) {
				digit1[i] %= 10;
				LCD_ShowChar(1, 1, 'E');
			} else {
				digit1[i + 1] += digit1[i] / 10;
				digit1[i] %= 10;
			}
		}
	}
	memset(digit2, 0, sizeof(char) * 14);
	LCD_ShowDigitArray(digit1, 1);
	LCD_Clear(2, 3, 14);
} 

void main() {
	LCD_Init();

	while(1) {
		key = MatrixKey();
		switch(key) {
		case 12: InsertDigit(0); break;
		case 14: Move(); break;
		case 7: Sum(); break;
		default:
			if(0 <= key && key <= 2) {
				InsertDigit(key + 1);
			} else if(4 <= key && key <= 6) {
				InsertDigit(key);
			} else if(8 <= key && key <= 10) {
				InsertDigit(key - 1);
			}
		}
	}
}